package cn.chiship.sdk.framework.velocity;

import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.exception.custom.SystemErrorException;
import org.apache.commons.io.output.FileWriterWithEncoding;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.File;
import java.io.StringWriter;
import java.util.Properties;

/**
 * Velocity工具类
 *
 * @author lijian
 */
public class VelocityUtil {

	private VelocityUtil() {

	}

	/**
	 * 根据模板生成文件
	 * @param inputVmFilePath 模板路径
	 * @param outputFilePath 输出文件路径
	 * @param context 上下文
	 * @throws Exception 异常
	 */
	public static void generate(String inputVmFilePath, String outputFilePath, VelocityContext context) {

		try {
			Properties properties = new Properties();
			properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, getPath(inputVmFilePath));
			Velocity.init(properties);
			Template template = Velocity.getTemplate(getFile(inputVmFilePath), "UTF-8");
			File outputFile = new File(outputFilePath);
			FileWriterWithEncoding writer = new FileWriterWithEncoding(outputFile, "UTF-8");
			template.merge(context, writer);
			writer.close();
		}
		catch (Exception ex) {
			throw new SystemErrorException(ex);
		}

	}

	/**
	 * 根据模板生成字符串
	 * @param inputVmFilePath 模板路径
	 * @param context 上下文
	 * @return 结果
	 * @throws Exception 异常
	 */
	public static String generate(String inputVmFilePath, VelocityContext context) {

		try {
			Properties properties = new Properties();
			properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, getPath(inputVmFilePath));
			Velocity.init(properties);
			Template template = Velocity.getTemplate(getFile(inputVmFilePath), "utf-8");
			StringWriter writer = new StringWriter();
			template.merge(context, writer);
			writer.close();
			return writer.toString();
		}
		catch (Exception ex) {
			throw new SystemErrorException(ex);
		}

	}

	/**
	 * 根据文件绝对路径获取目录
	 * @param filePath 路径
	 * @return 结果
	 */
	public static String getPath(String filePath) {
		String path = "";
		if (StringUtils.isNotBlank(filePath)) {
			path = filePath.substring(0, filePath.lastIndexOf("/") + 1);
		}

		return path;
	}

	/**
	 * 根据文件绝对路径获取文件
	 * @param filePath 路径
	 * @return 结果
	 */
	public static String getFile(String filePath) {
		String file = "";
		if (StringUtils.isNotBlank(filePath)) {
			file = filePath.substring(filePath.lastIndexOf("/") + 1);
		}

		return file;
	}

}
